import { makeObservable, observable, action, runInAction } from "mobx";

export abstract class BaseStore {
  isLoading = false;
  error: string | null = null;

  constructor() {
    makeObservable(this, {
      isLoading: observable,
      error: observable,
      setLoading: action,
      setError: action,
      clearError: action,
    });
  }

  setLoading = (loading: boolean) => {
    this.isLoading = loading;
  };

  setError = (error: string | null) => {
    this.error = error;
  };

  clearError = () => {
    this.error = null;
  };

  protected async executeAsync<T>(
    asyncFn: () => Promise<T>,
    options?: {
      onSuccess?: (data: T) => void;
      onError?: (error: Error) => void;
    }
  ): Promise<T | null> {
    try {
      this.setLoading(true);
      this.clearError();

      const result = await asyncFn();

      runInAction(() => {
        options?.onSuccess?.(result);
      });

      return result;
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : "Unknown error occurred";

      runInAction(() => {
        this.setError(errorMessage);
        options?.onError?.(error as Error);
      });

      return null;
    } finally {
      runInAction(() => {
        this.setLoading(false);
      });
    }
  }
}
